package com.lzxuni.modules.shiro.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.lzxuni.common.annotation.SysLog;
import com.lzxuni.common.constant.LogConstant;
import com.lzxuni.common.exception.LzxException;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.web.HttpContextUtils;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.oauth2.service.UserTokenService;
import com.lzxuni.modules.organization.entity.User;
import com.lzxuni.modules.organization.service.UserService;
import com.lzxuni.modules.shiro.ShiroUtils;
import com.lzxuni.modules.system.service.SysCaptchaService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class LoginController  extends BaseController {
	private static final Logger log    = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private SysCaptchaService sysCaptchaService;
	@Autowired
	private Producer producer;
	@Autowired
	private UserService userService;
	@Autowired
	private UserTokenService userTokenService;
	@RequestMapping(value = {"/"})
	public void index(HttpServletResponse response) throws IOException {
		response.sendRedirect("/index.html");
//		return "redirect:/index.html";
	}
	// 后台主页
	@RequestMapping("/index.html")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response,String token,String locale) {
		//保存cookie
		writeCookie(request,response, "token",token);
		ModelAndView mv = new ModelAndView("/Home/index");
		Cookie[] cookies = request.getCookies();
		String theme = "1";
		if(cookies!=null){
			for (Cookie cookie : cookies) {
				switch(cookie.getName()){
					case "Learn_ADMS_V6.1_UItheme":
						theme = cookie.getValue();
						break;
					default:
						break;
				}
			}
			switch(theme){
				case "1":
					mv.setViewName("/Home/index");
					break;
				case "2":
					mv.setViewName("/Home/index2");
					break;
				case "3":
					mv.setViewName("/Home/index3");
					break;
				case "4":
					mv.setViewName("/Home/index4");
					break;
				default:
					mv.setViewName("/Home/index");
					break;
			}
		}
		return mv;
	}
	// 主页包含内容页
	@RequestMapping("/Home/AdminDesktop")
	public ModelAndView adminDesktopTemp(String username) {
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//		ModelAndView mv = new ModelAndView("/Home/Welcome");
		ModelAndView mv = new ModelAndView("/Home/AdminDesktop");
		return mv;
	}

	// 用户session页面
	@RequestMapping("/login")
	public Object VerificationForm(HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("/Home/login");
//		try {
//			User user = getUser();
//			if(user!=null){
//				response.sendRedirect("/index.html");
//			}
//		} catch (Exception e) {
//		}
		return mv;
	}
	// 登陆页面
	@RequestMapping("/LR_LGManager/LGType/GetList")
	public Object GetList() {
		ModelAndView mv = new ModelAndView("/LR_LGManager/LGType/GetList");
		return mv;
	}

	// 图标页面
	@RequestMapping("/Utility/Icon")
	public Object Icon() {
		ModelAndView mv = new ModelAndView("/Utility/Icon");
		return mv;
	}

    /**
     * 传统登录
     */

    @SysLog(categoryId = LogConstant.LOGINID,module = "登陆",operateType = LogConstant.LOGIN)
    @RequestMapping("/login_o")
    public R login(String data, HttpServletRequest request) {
		JSONObject jsonObject = JSON.parseObject(data);
		String username = (String) jsonObject.get("username");
		String password = (String) jsonObject.get("password");
		String rememberMe = (String) jsonObject.get("rememberMe");
		boolean flag = false;
		if (StringUtils.isNotEmpty(rememberMe) && rememberMe.equalsIgnoreCase("on")) {
			flag = true;
		}
    	//1 构造token
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		token.setRememberMe(flag);
//		if(rememberMe==null){
//			token.setRememberMe(true);
//		}else{
//			token.setRememberMe(rememberMe);
//		}
		String info = "";
		// 2如果输入了验证码，那么必须验证；如果没有输入验证码，则根据当前用户判断是否需要验证码。
		try {
            Subject subject = ShiroUtils.getSubject();
            subject.login(token);
        }catch (UnknownAccountException e) {
			info = e.getMessage();
        }catch (IncorrectCredentialsException e) {
			info = "账号或密码不正确";
        }catch (LockedAccountException e) {
			info = "账号已被锁定,请联系管理员";
        }catch (AuthenticationException e) {
			info = "账户验证失败";
        }catch ( LzxException e) {
			info = e.getMessage();
		}
        if(StringUtils.isNotEmpty(info)){
			return R.error(info);
		}
		return R.ok().put("data","");
    }

	/**
	 * autho2登录
	 */
	@PostMapping("/login_o1")
	public R login(String data,HttpServletRequest request,HttpServletResponse response)throws IOException {
//		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
//		if(!captcha){
//			return R.error("验证码不正确");
//		}

		JSONObject jsonObject = JSON.parseObject(data);
		String username = (String) jsonObject.get("username");
		String password = (String) jsonObject.get("password");

//		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//		token.setRememberMe(true);


		User user = userService.queryByUserName(username);

		//账号不存在、密码错误
		SimpleHash passwordMd5 = new SimpleHash(ShiroUtils.hashAlgorithmName, password,
				user.getSecretkey(), ShiroUtils.hashIterations);
		if(user == null || !user.getPassword().equals(passwordMd5.toString())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getEnabledMark() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = userTokenService.createOrUpdateToken(user.getUserId());

		return R.ok().put("data",r);
	}
	public static void writeCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String value) {
		Cookie cookie = new Cookie(cookieName, value);
		cookie.setPath(request.getContextPath());
		cookie.setHttpOnly(true);
		response.addCookie(cookie);
	}

	/**
	 * 退出
	 */
	@RequestMapping("/logout.html")
	public R logout() {
		userTokenService.logout(getUserId());
		return R.ok();
	}

	@RequestMapping("/Home/VisitModule")
	public ModelAndView getMap(){
		ModelAndView mv = new ModelAndView("/Home/VisitModule");
		return mv;
	}
	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//保存到shiro session
		ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
	}

}
